package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
1.添加过滤器插件
* 2.定义路径匹配器 支持通配符
* 3.设置不需要进入过滤的网址集合
* 4.定义方法比较是否需要过滤
*
*/


@WebFilter(filterName = "loginCheckFilter2",urlPatterns = "/*")
@Slf4j
public class loginCheckFilter2 implements Filter {

    private static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();



    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;

        String uri = request.getRequestURI();

        log.info("本次请求为：{}",uri);

        //3.设置不需要进入过滤的网址集合
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        boolean judge = judge(uri,urls);

        if(judge){
            filterChain.doFilter(request,response);
            return;
        }
        //4.1判断"employee"的登陆状态，如果已登录则直接放行
        if(request.getSession().getAttribute("employee") !=null){
            log.info("已登录");

            long id = Thread.currentThread().getId();

            log.info("该线程的ID为：{}",id);

            Long userId = (Long)request.getSession().getAttribute("employee");

            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response);
            return;
        }

        //4.2判断"user"的登陆状态，如果已登录则直接放行
        if ( request.getSession().getAttribute("user")!=null) {
            log.info("已登录");

            long id = Thread.currentThread().getId();

            log.info("该线程ID为：{}",id);

            Long userId = (Long) request.getSession().getAttribute("user");

            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response);
            return;
        }

        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    private boolean judge(String uri,String[] urls) {
        for (String url : urls) {
            boolean result = PATH_MATCHER.match(url , uri);
            if(result){
                return true;
            }
        }
        return false;
    }
}
